"""
    与后台数据交互类
"""
import json
import logging

import requests
from src64.models.user_info import UserInfo
from src64.utils.encrypt_decrypt import decode, encode_data
from src64.models.check_sign_word import CheckSignWordResponse
from src64.models.save_report_response import SaveReportResponse
from src64.models.json_object import JSONOBJECT
from src64.models.upload_response import UploadResponse

"""
    数据请求统一封装
"""


class PostData:
    baseUrl: str
    headers: dict
    userInfo: UserInfo

    def __init__(self, conf, info):
        self.userInfo = info
        self.baseUrl = conf['post']['base_url']
        self.headers = {'Authorization': f"Bearer {self.userInfo.token}",
                        'Content-Type': 'application/json; charset=UTF-8'
                        }
        self.deptId = conf['post']['dept_id']
        self.room_no = conf['post']['room_no']

    async def post_data(self, url, params):
        """
        post请求统一封装
        :param url:
        :param params:
        :return:
        """
        logging.getLogger('main').info('请求路径:{},参数:{}'.format(url, params))
        try:
            res = requests.post(self.baseUrl + url, json=encode_data(params),
                                headers=self.headers)
            decode_text = decode(res.text)
            logging.getLogger('main').info('响应:{}'.format(decode_text))
            return json.loads(decode_text, object_hook=JSONOBJECT)
        except Exception as e:
            logging.getLogger('main').error('请求出错:{}'.format(e))
            return None

    async def upload_file(self, file_path) -> UploadResponse:
        """
        上传图片
        :param file_path:
        :return:
        """
        try:
            with open(file_path, 'rb') as file:
                files = {'file': (file_path, file)}
                res = requests.post(self.baseUrl + 'peisApi/admin/sys-file/uploadImage', files=files,
                                    headers={'Authorization': f"Bearer {self.userInfo.token}"})
                return json.loads(res.text, object_hook=JSONOBJECT)
        except Exception as e:
            logging.getLogger('main').error('上传图片出错:{}'.format(e))
            return None

    async def upload_file_bytes(self, file_bytes) -> UploadResponse:
        """
        上传图片
        :param file_path:
        :return:
        """
        try:
            files = {'file': ('report', file_bytes)}
            res = requests.post(self.baseUrl + 'peisApi/admin/sys-file/uploadImage', files=files,
                                headers={'Authorization': f"Bearer {self.userInfo.token}"})
            return json.loads(res.text, object_hook=JSONOBJECT)
        except Exception as e:
            logging.getLogger('main').error('上传图片出错:{}'.format(e))
            return None

    async def list_check_sign_word(self, reg_no, sex) -> CheckSignWordResponse:
        """
        根据体检号获取科室结论词
        :param reg_no:
        :param sex:
        :return:
        """
        return await self.post_data('peisApi/peis/patientCheckItem/listPatientCheckWithSignWord', {
            'registNo': reg_no,
            'deptId': self.deptId,
            'sex': sex
        })

    async def save_check_report(self, data) -> SaveReportResponse:
        """
        保存报告结果
        :param data:
        :return:
        """
        return await self.post_data('peisApi/peis/patientCheckResult/savePatientDeptCheckResult', data)

    async def complete_check(self, data):
        """
        完成分科检查
        :param data:
        :return:
        """
        return await self.post_data('peisApi/peis/guideInspectIntelligentQueue/subInspectDeptInspectComplete',
                                    {'roomNo': self.room_no, 'registNo': data})
